package com.xuanwei.rabbit_consume.handler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xuanwei.dao.entity.*;
import com.xuanwei.dao.mapper.*;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author jiangyong
 * @Description TODO
 * @Date 2019/7/25 17:12
 **/
@Component
public class OrderHandler {

    private XwOrderMapper orderMapper;

    private XwOrderRefundMapper orderRefundMapper;

    private XwOrderStatisticsMapper orderStatisticsMapper;

    private ProductHandler productHandler;

    private XwOrderRefundRecordMapper orderRefundRecordMapper;

    private XwOrderItemMapper orderItemMapper;

    private XwProductSkuMapper productSkuMapper;

    private XwProductMapper productMapper;

    private XwUserMapper userMapper;

    private XwOrderCommentMapper orderCommentMapper;

    public OrderHandler(XwOrderMapper orderMapper,
                        XwOrderRefundMapper orderRefundMapper,
                        XwOrderStatisticsMapper orderStatisticsMapper,
                        ProductHandler productHandler,
                        XwOrderRefundRecordMapper orderRefundRecordMapper,
                        XwOrderItemMapper orderItemMapper,
                        XwProductSkuMapper productSkuMapper,
                        XwProductMapper productMapper,
                        XwUserMapper userMapper,
                        XwOrderCommentMapper orderCommentMapper) {
        this.orderMapper = orderMapper;
        this.orderRefundMapper = orderRefundMapper;
        this.orderStatisticsMapper = orderStatisticsMapper;
        this.productHandler = productHandler;
        this.orderRefundRecordMapper = orderRefundRecordMapper;
        this.orderItemMapper = orderItemMapper;
        this.productSkuMapper = productSkuMapper;
        this.productMapper = productMapper;
        this.userMapper = userMapper;
        this.orderCommentMapper = orderCommentMapper;
    }


    /**
     * 用户没有支付
     *
     * @param orderId
     */
    public void notPay(Integer orderId) {
        XwOrder order = new XwOrder();
        order.setId(orderId);
        order.setStatus(7);
        orderMapper.updateById(order);
    }

    /**
     * 改变收货状态
     *
     * @param orderId 订单ID
     */
    public void receive(Integer orderId) {
        XwOrder order = new XwOrder();
        order.setId(orderId);
        order.setStatus(3);
        order.setReceiveTime(LocalDateTime.now());
        orderMapper.updateById(order);
    }

    /**
     * 关闭订单
     *
     * @param orderId 订单ID
     */
    @Transactional
    public void orderClose(Integer orderId) {
        XwOrder order = new XwOrder();
        order.setId(orderId);
        order.setStatus(6);
        order.setCloseTime(LocalDateTime.now());
        orderMapper.updateById(order);
        // 返回库存
        updateStock(orderId);

    }

    /**
     * 成功订单
     *
     * @param orderId 订单ID
     */
    @Transactional
    public void success(Integer orderId) {
        XwOrder _order = orderMapper.selectOne(new QueryWrapper<XwOrder>().select("id,user_id").eq("id", orderId));
        XwOrder order = new XwOrder();
        order.setId(orderId);
        order.setStatus(4);
        order.setUpdateTime(LocalDateTime.now());
        order.setCloseTime(LocalDateTime.now());
        orderMapper.updateById(order);
        List<XwOrderItem> orderItems = orderItemMapper.selectList(new QueryWrapper<XwOrderItem>().eq("order_id", order));
        XwUser user = userMapper.selectById(_order.getUserId());
        orderItems.forEach(orderItem -> {
            XwOrderComment orderComment = new XwOrderComment();
            orderComment.setComment("用户时间内没有评价,系统默认评价");
            orderComment.setCreateTime(LocalDateTime.now());
            orderComment.setImage("");
            orderComment.setLevel(0);
            orderComment.setOrderId(order.getId());
            orderComment.setOrderItemId(orderItem.getId());
            orderComment.setProductId(orderItem.getProductId());
            orderComment.setSkuName(orderItem.getSkuName());
            orderComment.setUserAvatar(user.getAvatarUrl());
            orderComment.setUserId(user.getId());
            orderComment.setUserNickname(user.getNickname());
            orderCommentMapper.insert(orderComment);
        });

    }

    /**
     * 订单支付成功
     *
     * @param orderId 订单ID
     */
    @Transactional
    public void orderSuccess(Integer orderId) {
        XwOrder order = orderMapper.selectOne(new QueryWrapper<XwOrder>()
                .select("id,actual_amount").eq("id", orderId));
        //修改订单状态
        order.setId(orderId);
        order.setStatus(1);
        order.setPayTime(LocalDateTime.now());
        orderMapper.updateById(order);
        //统计表
        LocalDateTime now = LocalDateTime.now();
        int year = now.getYear();
        int monthValue = now.getMonthValue();
        XwOrderStatistics orderStatistics = orderStatisticsMapper
                .selectOne(new QueryWrapper<XwOrderStatistics>()
                        .select("id,amount,refund,order_count")
                        .eq("statistics_year", year)
                        .eq("statistics_month", monthValue));
        if (orderStatistics == null) {
            orderStatistics = new XwOrderStatistics();
            orderStatistics.setOrderCount(1);
            orderStatistics.setAmount(order.getActualAmount());
            orderStatistics.setStatisticsMonth(monthValue);
            orderStatistics.setStatisticsYear(year);
            orderStatistics.setUpdateTime(LocalDateTime.now());
            orderStatistics.setCreateTime(LocalDateTime.now());
            orderStatisticsMapper.insert(orderStatistics);
        } else {
            orderStatistics.setUpdateTime(LocalDateTime.now());
            orderStatistics.setOrderCount(orderStatistics.getOrderCount() + 1);
            orderStatistics.setAmount(orderStatistics.getAmount().add(order.getActualAmount()));
            orderStatisticsMapper.updateById(orderStatistics);
        }
    }


    @Transactional
    public void orderRefundSuccess(Integer refundId) {
        XwOrderRefund orderRefund = new XwOrderRefund();
        orderRefund.setId(refundId);
        //修改退款成功
        orderRefund.setStatus(4);
        orderRefundMapper.updateById(orderRefund);

        //添加退款记录
        XwOrderRefundRecord orderRefundRecord = new XwOrderRefundRecord();
        orderRefundRecord.setCreateTime(LocalDateTime.now());
        orderRefundRecord.setOrderRefundId(refundId);
        orderRefundRecord.setMessage("退款已成功到账");
        orderRefundRecordMapper.insert(orderRefundRecord);

        LocalDateTime now = LocalDateTime.now();
        int year = now.getYear();
        int monthValue = now.getMonthValue();

        XwOrderStatistics orderStatistics = orderStatisticsMapper
                .selectOne(new QueryWrapper<XwOrderStatistics>()
                        .select("id,amount,refund,order_count")
                        .eq("statistics_year", year)
                        .eq("statistics_month", monthValue));
        XwOrderRefund refund = orderRefundMapper.selectById(refundId);
        XwOrder order = orderMapper.selectOne(new QueryWrapper<XwOrder>()
                .select("id,actual_amount").eq("id", refund.getOrderId()));

        if (orderStatistics == null) {
            orderStatistics = new XwOrderStatistics();
            orderStatistics.setRefund(order.getActualAmount());
            orderStatistics.setStatisticsMonth(monthValue);
            orderStatistics.setStatisticsYear(year);
            orderStatistics.setUpdateTime(LocalDateTime.now());
            orderStatistics.setCreateTime(LocalDateTime.now());
            orderStatisticsMapper.insert(orderStatistics);
        } else {
            orderStatistics.setUpdateTime(LocalDateTime.now());
            orderStatistics.setOrderCount(orderStatistics.getOrderCount() - 1);
            orderStatistics.setAmount(orderStatistics.getAmount().subtract(order.getActualAmount()));
            orderStatisticsMapper.updateById(orderStatistics);
        }


        //修改商品库存
        updateStock(order.getId());

    }

    /**
     * 修改库存
     *
     * @param orderId 订单ID
     */
    private void updateStock(Integer orderId) {
        List<XwOrderItem> orderItems = orderItemMapper.selectList(new QueryWrapper<XwOrderItem>()
                .select("id,product_id,sku_id,`count`")
                .eq("order_id", orderId));

        orderItems.forEach(s -> {
            Integer productId = s.getProductId();
            Integer skuId = s.getSkuId();
            XwProductSku productSku = productSkuMapper.selectOne(new QueryWrapper<XwProductSku>()
                    .select("id,stock")
                    .eq("id", skuId));
            productSku.setStock(productSku.getStock() + s.getCount());
            productSku.setUpdateTime(LocalDateTime.now());
            productSkuMapper.updateById(productSku);

            XwProduct product = productMapper.selectOne(new QueryWrapper<XwProduct>()
                    .select("id,stock")
                    .eq("id", productId));
            product.setStock(product.getStock() + s.getCount());
            product.setUpdateTime(LocalDateTime.now());
            productMapper.updateById(product);
            productHandler.insert(product.getId());
        });

    }
}
